import time, sys, pygame, os, signals, usb
from pygame.locals import *

pygame.init()
window = pygame.display.set_mode((800, 600)) # pygame.FULLSCREEN| pygame.HWACCEL | pygame.FULLSCREEN

from pydispatch import dispatcher
from config import Env


class GUI(object):
    def __init__(self, env):
        self.env = env
        self.surface = pygame.display.get_surface()
        self.book = env.BOOK(mule=self)
        pygame.surface.Surface.convert(self.surface)
        (self.X, self.Y) = self.surface.get_width(), self.surface.get_height()
    
        dispatcher.connect(self.button_clicked, signal=signals.button_clicked)
        if self.env.TEST_MODE: dispatcher.connect(self.test_key, signal=signals.test_key)
        dispatcher.send(signal=signals.turn_page, page=self.book.Welcome)

    def input(self, events):
        for event in events:
            x,y = pygame.mouse.get_pos()
            signal = None
            if event.type == KEYDOWN:
                if event.key in self.env.TEST_KEYS: (signal, data, tag) = signals.test_key, {'key':event.key}, 'test'
                if event.key == K_q: sys.exit(0)
            if event.type == MOUSEBUTTONDOWN: (signal, data, tag) = signals.mouse_clicked, {'x':x, 'y':y}, 'click'
            if event.type == MOUSEMOTION    : (signal, data, tag) = signals.mouse_motion,  {'x':x, 'y':y}, 'mouse move'
            if signal:
                if self.env.TEST_MODE and not event.type == MOUSEMOTION: print "Sending signal: %s" % tag
                dispatcher.send(signal=signal, **data)

    def screen_blit(self):
        self.book.blit()
        pygame.display.flip()

    # H a n d l e r s
    def test_key(self, key):
        if key==K_m:
            x,y = pygame.mouse.get_pos()
            print 'mouse xy:', x, y

    def button_clicked(self, button):
        if self.env.TEST_MODE: print 'Button %s, clicked' % button.tag
        if button.tag == 'quit':
            sys.exit(0)


if __name__ == '__main__':
    env = Env()
    pygame.display.set_caption(env.CAPTION)
    app = GUI(env)

    (poll_time, frm_time) = 0, 0
    while 1:
        frm_time += env.FRAME_CLOCK.tick()
        poll_time += env.FRAME_CLOCK.tick()
        if frm_time > env.FPS:
            app.input(pygame.event.get())
            frm_time = 0
        if poll_time > env.USB_POLL_INTERVAL:
            poll_time = 0
            app.screen_blit()
            dispatcher.send(signals.poll_usb)